package com.szp.drug.config;

import com.google.gson.Gson;
import com.szp.drug.util.ResultEntity;
import com.szp.drug.exception.AccountAddDuplicateKeyException;
import com.szp.drug.exception.AccountEditDuplicateKeyException;
import com.szp.drug.util.DrugUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 异常处理器
 * @author SuZePing
 * @create 2021-01-12 8:35
 * @E-mail suzeping10@126.com
 */
@ControllerAdvice
public class DrugExceptionResolver {

	/**
	 * 修改时用户名重复异常处理
	 * @param exception
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ExceptionHandler(AccountEditDuplicateKeyException.class)
	public ModelAndView resolveAccountEditDuplicateKeyException(AccountEditDuplicateKeyException exception, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String viewName = "system-error";
		return commonResolve(viewName, exception, request, response);
	}

	/**
	 * 新增时用户名重复异常处理
	 * @param exception
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ExceptionHandler(AccountAddDuplicateKeyException.class)
	public ModelAndView resolveAccountAddDuplicateKeyException(AccountAddDuplicateKeyException exception, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String viewName = "admin-add";
		return commonResolve(viewName, exception, request, response);
	}

	/**
	 * 未登录就访问被保护资源异常处理
	 * @param exception
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@ExceptionHandler(Exception.class)
	public ModelAndView resolveException(Exception exception, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String viewName = "system-error";
		return commonResolve(viewName, exception, request, response);
	}

	/**
	 * 通用的异常返回类
	 * @param viewName	跳转的视图
	 * @param exception	异常类型
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	private ModelAndView commonResolve(String viewName,Exception exception, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (DrugUtil.judgeRequestType(request)){
			ResultEntity<Object> error = ResultEntity.error(exception.getMessage());
			String errorJson = new Gson().toJson(error);
			response.getWriter().write(errorJson);
			// 已经通过response返回响应，不需要返回ModelAndView
			return null;
		}
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("exception",exception);
		modelAndView.setViewName(viewName);
		return modelAndView;
	}
}
